package com.geline.mybatisplus.interceptor.inner;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.geline.mybatisplus.annotation.BeforeDelete;
import com.geline.mybatisplus.annotation.BeforeInsert;
import com.geline.mybatisplus.annotation.BeforeUpdate;
import com.geline.cloud.util.DynamicSqlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;

/**
 * 前置拦截器
 * @BeforeInsert
 * @BeforeUpdate
 * @BeforeDelete 逻辑删除不会进入
 *
 * @author: mx
 * @date: 2024-09-06 17:10
 */
@Slf4j
public class BeforeEntityInterceptor implements InnerInterceptor {

    private JdbcTemplate jdbcTemplate;

    public BeforeEntityInterceptor(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        SqlCommandType sct = ms.getSqlCommandType();
        if(ms.getId().contains("deleteById")){
            //com.geline.cloud.system.mapper.SysNoticeMapper
            String mapper = ms.getId().replace(".deleteById", "");
            Class<BaseMapper> mapperClass = ClassUtil.loadClass(mapper);
            BaseMapper baseMapper = SpringUtil.getBean(mapperClass);
            Object entity = baseMapper.selectById((Serializable) parameter);
            this.handleDelete(entity);
        } else if(ms.getId().contains("deleteBatchIds")){
            String mapper = ms.getId().replace(".deleteBatchIds", "");
            Class<BaseMapper> mapperClass = ClassUtil.loadClass(mapper);
            BaseMapper baseMapper = SpringUtil.getBean(mapperClass);

            Object object = parameter;
            if(parameter instanceof MapperMethod.ParamMap){
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                if(map.containsKey("et")){
                    object = map.get("et");
                }else if(map.containsKey("param1")){
                    object = map.get("param1");
                }
            }
            Collection list = (Collection)object;
            for(Object id : list){
                Object entity = baseMapper.selectById((Serializable) id);
                this.handleDelete(entity);
            }
        }else if (sct == SqlCommandType.INSERT) {
            this.handleEntity(sct, parameter);
        }else if (sct == SqlCommandType.UPDATE) {
            Object object = parameter;
            if(parameter instanceof MapperMethod.ParamMap){
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                if(map.containsKey("et")){
                    object = map.get("et");
                }
            }
            this.handleEntity(sct, object);
        }
    }

    protected void handleEntity(SqlCommandType sct, Object entity) {
        if (sct == SqlCommandType.INSERT) {
            BeforeInsert[] annArray = entity.getClass().getAnnotationsByType(BeforeInsert.class);
            if(annArray != null && annArray.length > 0) {
                for (BeforeInsert annotation : annArray) {
                    this.handleInsert(annotation, entity);
                }
            }
        }else if (sct == SqlCommandType.UPDATE) {
            BeforeUpdate[] annArray = entity.getClass().getAnnotationsByType(BeforeUpdate.class);
            if(annArray != null && annArray.length > 0) {
                for (BeforeUpdate annotation : annArray) {
                    this.handleUpdate(annotation, entity);
                }
            }
        }
    }

    protected void handleInsert(BeforeInsert annotation, Object entity){
        String countSql = annotation.countSql();
        if(StrUtil.isNotBlank(countSql)){
            String sql = DynamicSqlUtil.parseSQL(countSql, BeanMap.create(entity));
            if(sql.contains("#{") || sql.contains("${")){
                log.warn("@BeforeInsert can not run sql = {}", sql);
            }else {
                Long number = jdbcTemplate.queryForObject(sql, Long.class);
                if(number!=null && number>0){
                    throw new RuntimeException(annotation.errorMsg());
                }
                log.info("@BeforeInsert = {}", sql);
            }
        }
    }

    protected void handleUpdate(BeforeUpdate annotation, Object entity){
        String countSql = annotation.countSql();
        if(StrUtil.isNotBlank(countSql)){
            String sql = DynamicSqlUtil.parseSQL(countSql, BeanMap.create(entity));
            if(sql.contains("#{") || sql.contains("${")){
                log.warn("@BeforeUpdate can not run sql = {}", sql);
            }else {
                Long number = jdbcTemplate.queryForObject(sql, Long.class);
                if(number!=null && number>0){
                    throw new RuntimeException(annotation.errorMsg());
                }
                log.info("@BeforeUpdate = {}", sql);
            }
        }
    }

    protected void handleDelete(Object entity){
        BeforeDelete[] annArray = entity.getClass().getAnnotationsByType(BeforeDelete.class);
        if(annArray != null && annArray.length > 0) {
            for (BeforeDelete annotation : annArray) {
                String countSql = annotation.countSql();
                if(StrUtil.isNotBlank(countSql)){
                    String sql = DynamicSqlUtil.parseSQL(countSql, BeanMap.create(entity));
                    if(sql.contains("#{") || sql.contains("${")){
                        log.warn("@BeforeDelete can not run sql = {}", sql);
                    }else {
                        Long number = jdbcTemplate.queryForObject(sql, Long.class);
                        if(number!=null && number>0){
                            throw new RuntimeException(annotation.errorMsg());
                        }
                        log.info("@BeforeDelete = {}", sql);
                    }
                }
            }
        }
    }
}
